﻿using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.Util.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.Excel
{
    /// <summary>
    /// 实体映射器
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class EntitySheetMapper<TEntity> : SheetMapper<TEntity>
    {


        public EntitySheetMapper(ExcelMapper excelMapper, string sheetName) : base(excelMapper, sheetName)
        {
            ExcelColumns = new List<ColumnOption<TEntity>>();
        }

        public override object GetRowCell(int rowIndex, TEntity obj, ColumnOption<TEntity> columnOption)
        {
            string val = string.Empty;
            var type = typeof(TEntity);
            var properties = type.GetProperties();
            if (!string.IsNullOrWhiteSpace(columnOption.FieldName))
            {
                foreach (var p in properties)
                {
                    if (columnOption.FieldName.ToLower() == p.Name.ToLower())
                    {
                        val = p.GetValue(obj, null).ToString();
                        break;
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(columnOption.ColumnName))
            {
                foreach (var p in properties)
                {
                    if (columnOption.ColumnName.ToLower() == p.Name.ToLower())
                    {
                        val = p.GetValue(obj, null).ToString();
                        break;
                    }
                }
            }
            return val;
        }

        public override void Put(object data)
        {
            if (!(data is List<TEntity>)) throw new ArgumentNullException("数据源为空");
            DataSources = data as List<TEntity>;
            //当没有为数据源配置时，则以数据源为标准执行数据导出
            if (ExcelColumns == null || !ExcelColumns.Any())
            {
                if (ExcelColumns == null) ExcelColumns = new List<ColumnOption<TEntity>>();
                var type = typeof(TEntity);
                var properties = type.GetProperties();
                foreach (var p in properties)
                {   
                    ColumnOption<TEntity> columnOption;
                    // 检查属性是否有DescriptionAttribute特性
                    DescriptionAttribute attribute = (DescriptionAttribute)p.GetCustomAttribute(typeof(DescriptionAttribute));
                    if (attribute != null)
                    {
                        columnOption = new ColumnOption<TEntity>(attribute.Description, p.Name);
                    }
                    else {
                        columnOption = new ColumnOption<TEntity>(p.Name);
                    }
                    ExcelColumns.Add(columnOption);
                }
            }
        }

    }
}
